#!/bin/bash

#DPATH contains the PATH where all files are stored e.g. the following path
export DPATH=/home/olpc/cdmamodem

#Installs the required packages: wvdial, ppp and libwvstreams, if not found
if rpm -q wvdial&>/dev/null
then
echo "wvdial is already present" &> $DPATH/log
else
echo "wvdial not present.Installing it.." &> $DPATH/log
for i in `ls $DPATH/*.rpm`;do rpm -i $i 1>>$DPATH/log 2>>$DPATH/log ;done &> /dev/null
fi

#Function to kill existing services to be called if device is busy
function killl {
killall -9 pppd
killall -9 ping
}

#End any preexising dialer service related to modem 
#End wvdial
ps ax|grep wvdial 1>>$DPATH/log && killall -9 wvdial 2>> $DPATH/log 1>> $DPATH/log && sleep 2
killall wvdialconf 1>>$DPATH/log 2>>$DPATH/log
killall pppd 1>>$DPATH/log 2>>$DPATH/log 
killall connect 1>>$DPATH/log 2>>$DPATH/log
kill -9 `cat /var/run/modem.pid` &>/dev/null

#The process id is saved in the following location
echo $$>/var/run/modem.pid

#Now run connect program provided with the modem
cd $DPATH
while read line
do 
    echo $line 1>>$DPATH/log 2>>$DPATH/log
    echo $line|grep "Found"&>/dev/null && break&>/dev/null
    echo $line|grep "busy"&>/dev/null && killl
done< <($DPATH/connect 2>&1)

#Disconnect from the mesh network and connect to internet using PPP
ifconfig msh0 down
killall connect &>/dev/null
ps ax|grep wvdial>&/dev/null && killall  -9 wvdial&>/dev/null && sleep 2
while read line
do  
        echo $line 1>>$DPATH/log  2>>$DPATH/log        
        echo $line|awk '/DNS/ {print "nameserver "$5}' >> /etc/resolv.conf 
        echo -en "Please Wait....Connecting..\r"
        echo $line|grep "secondary DNS"&>/dev/null && echo -e "\nConnected\t\t   " && break&>/dev/null
done< <(wvdial --config $DPATH/cdu680config 2>&1)
